/**
 * 存储工具函数
 * 封装localStorage和sessionStorage的操作
 */

/**
 * 本地存储类
 */
class Storage {
  private storage: globalThis.Storage
  private prefix: string

  /**
   * 构造函数
   * @param storage 存储对象，localStorage或sessionStorage
   * @param prefix 键前缀，默认为'coal_mall_'
   */
  constructor(storage: globalThis.Storage, prefix = 'coal_mall_') {
    this.storage = storage
    this.prefix = prefix
  }

  /**
   * 获取完整的键名
   * @param key 键名
   * @returns 添加前缀后的完整键名
   */
  private getKey(key: string): string {
    return `${this.prefix}${key}`
  }

  /**
   * 设置存储项
   * @param key 键名
   * @param value 值
   * @param expire 过期时间（毫秒），可选
   */
  set<T>(key: string, value: T, expire?: number): void {
    const stringData = JSON.stringify({
      value,
      expire: expire ? Date.now() + expire : null
    })
    this.storage.setItem(this.getKey(key), stringData)
  }

  /**
   * 获取存储项
   * @param key 键名
   * @param defaultValue 默认值，当获取失败时返回
   * @returns 存储的值或默认值
   */
  get<T>(key: string, defaultValue?: T): T | undefined {
    const item = this.storage.getItem(this.getKey(key))
    if (item) {
      try {
        const data = JSON.parse(item)
        const { value, expire } = data
        // 检查是否过期
        if (expire && expire < Date.now()) {
          this.remove(key)
          return defaultValue
        }
        return value as T
      } catch (e) {
        console.error('Error parsing storage item:', e)
        return defaultValue
      }
    }
    return defaultValue
  }

  /**
   * 移除存储项
   * @param key 键名
   */
  remove(key: string): void {
    this.storage.removeItem(this.getKey(key))
  }

  /**
   * 清除所有带前缀的存储项
   */
  clear(): void {
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i)
      if (key && key.startsWith(this.prefix)) {
        this.storage.removeItem(key)
        i-- // 删除后索引会变化，需要调整
      }
    }
  }

  /**
   * 获取所有存储项
   * @returns 所有存储项的键值对
   */
  getAll(): Record<string, any> {
    const result: Record<string, any> = {}
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i)
      if (key && key.startsWith(this.prefix)) {
        const shortKey = key.slice(this.prefix.length)
        result[shortKey] = this.get(shortKey)
      }
    }
    return result
  }
}

// 创建localStorage实例
export const localStore = new Storage(localStorage)

// 创建sessionStorage实例
export const sessionStore = new Storage(sessionStorage)

/**
 * 设置cookie
 * @param name cookie名称
 * @param value cookie值
 * @param days 过期天数
 * @param path cookie路径
 */
export function setCookie(name: string, value: string, days = 7, path = '/'): void {
  const expires = new Date(Date.now() + days * 864e5).toUTCString()
  document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=${path}`
}

/**
 * 获取cookie
 * @param name cookie名称
 * @returns cookie值
 */
export function getCookie(name: string): string | null {
  const nameEQ = `${name}=`
  const ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') c = c.substring(1, c.length)
    if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length))
  }
  return null
}

/**
 * 删除cookie
 * @param name cookie名称
 * @param path cookie路径
 */
export function removeCookie(name: string, path = '/'): void {
  setCookie(name, '', -1, path)
}